package com.ls.system.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ls.common.*;
import com.ls.system.entity.SysMenu;
import com.ls.system.entity.SysPermission;
import com.ls.system.service.SysMenuService;
import com.ls.system.service.SysPermissionService;
import com.ls.system.vo.SysPermissionVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author ls
 * @since 2025-04-15
 */
@RestController
@RequestMapping("/permission")
public class SysPermissionController {

    @Autowired
    private SysPermissionService sysPermissionService;

    @Autowired
    private SysMenuService sysMenuService;

    @RequestMapping("/list")
    public DataGridView loadAllPermission(
            PageModel pageModel,
            @RequestParam(required = false) Integer menuId // 接收父菜单ID
    ) {
        Page<SysPermission> page = new Page<>(pageModel.getPage(), pageModel.getLimit());
        QueryWrapper<SysPermission> queryWrapper = new QueryWrapper<>();

        // 如果传入了 menuId，查询该菜单及其所有子菜单的权限
        if (menuId != null) {
            // 1. 获取当前菜单及其所有子菜单ID
            List<Integer> subMenuIds = sysMenuService.getAllSubMenuIds(menuId);

            // 2. 使用 IN 条件过滤权限
            if (!subMenuIds.isEmpty()) {
                queryWrapper.in("menu_id", subMenuIds);
            }
        }

        // 3. 执行分页查询
        Page<SysPermission> result = sysPermissionService.page(page, queryWrapper);

        // 4. 转换为 VO 并填充菜单名称
        List<SysPermissionVO> voList = result.getRecords().stream()
                .map(permission -> {
                    SysPermissionVO vo = new SysPermissionVO();
                    BeanUtils.copyProperties(permission, vo);
                    // 获取菜单名称（需处理 menuId 为 null 的情况）
                    if (permission.getMenuId() != null) {
                        SysMenu menu = sysMenuService.getById(permission.getMenuId());
                        vo.setMenuName(menu != null ? menu.getTitle() : "未知菜单");
                    }
                    return vo;
                }).collect(Collectors.toList());

        return new DataGridView(result.getTotal(), voList);
    }

    @RequestMapping("/add")
    public ResultObj add(@RequestBody SysPermission sysPermission) {
        System.out.println("Received permission data: " + sysPermission);
        boolean save = sysPermissionService.save(sysPermission);
        if (save) return ResultObj.ADD_SUCCESS;
        return ResultObj.ADD_ERROR;
    }

    @RequestMapping("/update")
    public ResultObj update(@RequestBody SysPermission sysPermission) {
        boolean save = sysPermissionService.updateById(sysPermission);
        if (save) return ResultObj.UPDATE_SUCCESS;
        return ResultObj.UPDATE_ERROR;
    }

    @RequestMapping("/delete")
    public ResultObj delete(SysPermission sysPermission) {
        boolean save = sysPermissionService.removeById(sysPermission.getId());
        if (save) return ResultObj.DELETE_SUCCESS;
        return ResultObj.DELETE_ERROR;
    }

    @RequestMapping("/loadPermissionManagerLeftTreeJson")
    public DataGridView loadPermissionManagerLeftTreeJson() {
        // 获取所有菜单数据
        List<SysMenu> menuList = sysMenuService.list();
        List<TreeNode> treeNodes = new ArrayList<>();

        // 添加根节点
        treeNodes.add(new TreeNode(0, -1, "所有菜单", true));

        // 构建菜单树
        for (SysMenu menu : menuList) {
            TreeNode node = new TreeNode(
                    menu.getId(),
                    menu.getPid(),
                    menu.getTitle(),
                    sysMenuService.count(new QueryWrapper<SysMenu>().eq("pid", menu.getId())) > 0
            );
            treeNodes.add(node);
        }
        return new DataGridView(treeNodes);
    }
}

